package ru.hangman.donkeykong;

import java.io.IOException;

import org.anddev.andengine.engine.Engine;
import ru.hangman.donkeykong.background.*;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.graphics.Point;
import android.util.Log;

import ru.hangman.donkeykong.logic.LevelRepresentation;
import ru.hangman.donkeykong.persons.DonkeyKong;

public class DonkeyKongActivity extends BaseGameActivity implements IOnSceneTouchListener {
    // ===========================================================
    // Constants
    // ===========================================================


    private static final int CAMERA_WIDTH = 720;
    private static final int CAMERA_HEIGHT = 480;


    // ===========================================================
    // Fields
    // ===========================================================


    private Camera camera;

	private LevelRepresentation level;
	
    private DonkeyKong kong;
    private Background background;
    
    // ===========================================================
    // Constructors
    // ===========================================================


    // ===========================================================
    // Getter & Setter
    // ===========================================================


    // ===========================================================
    // Methods for/from SuperClass/Interfaces
    // ===========================================================


    @Override
    public Engine onLoadEngine() {
            this.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
            return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.camera));
    }


    @Override
    public void onLoadResources() {
    		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

    		try {
				level = new LevelRepresentation(getAssets().open("representation/level.xml"));
			} catch (IOException e) {
				Log.e("onLoadResources", String.format("Error while creating level representation: %s", e.getMessage()));
				e.printStackTrace();
			}
    		
    		kong = new DonkeyKong(this);
    		
    		background = new Background(this, CAMERA_HEIGHT, CAMERA_WIDTH);
            background.addTexture(512, 512, "game_scene_view_00.png");
            background.addTexture(512, 512, "game_scene_view_01.png");
            background.addTexture(512, 512, "game_scene_view_02.png");
            background.addTexture(512, 512, "game_scene_view_03.png");
            kong.setMaximumOffset(background.getBackgroundLength() - CAMERA_WIDTH);
    }


    @Override
    public Scene onLoadScene() {
            this.mEngine.registerUpdateHandler(new FPSLogger());

            final Scene scene = new Scene();

            background.draw(scene, kong.getSceneOffset());
            
            Point currentPosition = new Point(kong.getSceneOffset(), 0);
            LevelRepresentation.PointDescription pointDesc = level.getFixedPointFor(currentPosition);
            if(kong.processStepPointDescription(currentPosition, pointDesc, CAMERA_WIDTH/2))
            	kong.update(scene);

            scene.setOnSceneTouchListener(this);
            scene.setOnSceneTouchListenerBindingEnabled(true);
            
            scene.registerUpdateHandler(new IUpdateHandler() {
				@Override
				public void onUpdate(float pSecondsElapsed) {
					if(!kong.setLastUpdateTime(pSecondsElapsed, level, CAMERA_WIDTH/2))
						return;
					int offset = kong.getSceneOffset();
					background.update(offset);
					Scene scene = DonkeyKongActivity.this.getEngine().getScene();
					scene.sortChildren();
					kong.update(scene);
				}

				@Override
				public void reset() {
					Log.d("DonkeyKongActivity.onLoadScene", "Scene update handler reset.");
				}
            });
            
            scene.sortChildren();
            return scene;
    }


    @Override
    public void onLoadComplete() {
    }

    @Override
    public boolean onSceneTouchEvent(final Scene scene, final TouchEvent event) {
    	float x = event.getX()/CAMERA_WIDTH;
    	float y = event.getY()/CAMERA_HEIGHT;
    	
    	if((x < 0.3) && (y > 0.3) && (y < 0.7)) {
    		// Turn left pressed.
    		if(event.isActionDown())
    			kong.pullToLeft();
    		else if(event.isActionUp())
    			kong.stop();
    		if(event.isActionDown() || event.isActionUp())
    			kong.update(scene);
    	}
    	else if((x > 0.7) && (y > 0.3) && (y < 0.7)) {
    		// Turn right pressed.
    		if(event.isActionDown())
    			kong.pullToRight();
    		else if(event.isActionUp())
    			kong.stop();
    		if(event.isActionDown() || event.isActionUp())
    			kong.update(scene);
    	}
    	else {
    		kong.stop();
    		kong.update(scene);
    	}
        return true;
    }
    
    // ===========================================================
    // Methods
    // ===========================================================
    
    /*private void processPointDescription(Point sourcePoint, LevelRepresentation.PointDescription pointDescription, Scene scene) {
		//Make decision is new point acceptable.
		kong.processStepPointDescription(sourcePoint, pointDescription, scene, CAMERA_WIDTH/2);
    }*/

    // ===========================================================
    // Inner and Anonymous Classes
    // ===========================================================
}